from utils.prettyrepr import prettify_class


@prettify_class
class SolverInterruptManager(object):
    """
    This object manages solver interrupts. It maintains a queue of interrupt messages and
    associated solver state transitions.
    """
    def __init__(self, solver):
        self.solver = solver
        self.messages = []
        self.actions = []

    def __info__(self):
        return self.messages

    def __len__(self):
        return len(self.messages)

    def __nonzero__(self):
        return len(self.messages) > 0

    def clear(self):
        del self.messages[:]
        del self.actions[:]

    reset = clear

    def append(self, message, action=None):
        """Add a new interrupt to the solver. 'message' should describe the reason for the
        interrupt, and 'action' should be a solver transition symbol, normally ACTION.PAUSE or
        ACTION.FINISH (defined in statemachine.py), but None is a possible value, meanining that
        no action should be taken for that interrupt."""
        self.messages.append(message)
        self.actions.append(action)

    add = append

    def report(self):
        info = self.solver.log.info
        for message in self.messages:
            info(message)

    def apply(self, report=True):
        result = None
        for action in self.actions:
            if action is not None:
                result = self.solver.input(action)
        if report:
            self.report()
        return result
